<template>
  <!-- 修改标签表单 -->
  <el-dialog
    :visible.sync="dialogVisible"
    width="40%"
    @close="close"
    :title="title">

    <el-form
      ref="tagForm"
      :rules="tagFormRules"
      status-icon
      :model="tag"
      label-width="100px">

      <el-form-item label="标签名称：" prop="name">
        <el-input maxlength="30" show-word-limit v-model="tag.name" />
      </el-form-item>

    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button @click="close">取消</el-button>
      <el-button type="primary" @click="saveOrUpdate">确定</el-button>
    </div>

  </el-dialog>
</template>

<script>
  import { getTagById, updateTag, saveTag } from '@/api/tag'
  import { validNormal } from '@/utils/validate'

  export default {
    data() {

      //检验标题名称
      const validateName = (rule, value, callback) => {
        if (value.length < 3 || value.length > 30 || !value || !validNormal(value) ){
          callback(new  Error("请输入正确的问答标签，长度要求为3-30，且不能输入特殊字符"))
        }
        else callback()
      }

      return {
        title: '',
        dialogVisible: false,
        tag: {
          id: '',
          name: ''
        },
        //检验规则
        tagFormRules:{
          name:[{validator: validateName,trigger: 'blur'}],
        }
      }
    },

    methods: {
      open(tagId) {
        this.dialogVisible = true
        if (tagId) {
          this.tag.id = tagId
          this.title = '修改问答标签'
          getTagById(tagId).then(result => {
            this.tag = result.data.item
            delete this.tag.gmtCreate
            delete this.tag.gmtModified
          })
        }
        else {
          this.title = '新增问答标签'
        }
      },

      close() {
        this.$refs.tagForm.resetFields();
        this.dialogVisible = false
        // 重置表单
        this.resetForm()
      },

      resetForm() {
        this.tag.id = ''
        this.tag.name = ''
      },

      saveOrUpdate() {
        this.$refs.tagForm.validate((valid) => {
          if (valid) {
            //检验通过
            if (this.tag.id){
              this.update()
            }
            else {
              this.save()
            }
          }
          else {
            return false;
          }
        })
      },

      save(){
        saveTag(this.$qs.stringify(this.tag)).then(result => {
          this.$message({
            type: 'success',
            message: '新增成功！'
          })
          // 关闭组件
          this.close()
          // 调用父组件监听函数
          this.$emit('onSaveSuccess')
        })
      },

      update(){
        updateTag(this.tag.id,this.$qs.stringify(this.tag)).then(result => {
          this.$message({
            type: 'success',
            message: '修改成功！'
          })
          // 关闭组件
          this.close()
          // 调用父组件监听函数
          this.$emit('onSaveSuccess')
        })
      }
    }
  }
</script>

<style scoped>

</style>
